package com.healthfitness.floating.ui.listener

import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
import kotlin.math.abs

/**
 * 拖拽移动监听
 * view.setOnTouchListener(DragMoveListener(windowManager))
 * 使view具有移动拖拽更新位置功能
 */
class DragMoveListener(private val windowManager: WindowManager): View.OnTouchListener {
    private var initialX = 0
    private var initialY = 0 //初始位置中心偏上
    private var initialTouchX = 0f
    private var initialTouchY = 0f
    override fun onTouch(view: View, event: MotionEvent): Boolean {
        val params = view.layoutParams as WindowManager.LayoutParams
        return when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                initialX = params.x
                initialY = params.y
                initialTouchX = event.rawX
                initialTouchY = event.rawY
                true
            }

            MotionEvent.ACTION_MOVE -> {
                val deltaX = (event.rawX - initialTouchX).toInt()
                val deltaY = (event.rawY - initialTouchY).toInt()
                params.x = initialX + deltaX
                params.y = initialY + deltaY
                params.gravity = Gravity.NO_GRAVITY //取消布局限制
                windowManager.updateViewLayout(view, params)
                true
            }

            MotionEvent.ACTION_UP -> {
                // 判断是否为点击事件（移动距离小于阈值）
                val tolerance = ViewConfiguration.get(view.context).scaledTouchSlop
                val deltaX = (event.rawX - initialTouchX).toInt()
                val deltaY = (event.rawY - initialTouchY).toInt()
                if (abs(deltaX) < tolerance && abs(deltaY) < tolerance) {
                    view.performClick() // 触发点击事件
                }
                true
            }

            else -> false
        }
    }
}